extends NodeState

@export var enemy: BasicEnemy


# 是否正在准备攻击
var is_pre_attack: float = false
# 进入当前状态的时间
var enter_time: float = 0.0
# 最后一次攻击时间
var last_attack_time: float = 0.0
# 二段攻击时间
var last_alt_attack_time: float = 0.0
# 是否进行二段攻击
var punch_alt: bool


func _on_process(delta : float) -> void:
	if is_pre_attack:
		process_pre_attack(delta)
	else:
		process_attack()

	process_animation()
	process_punch_coillder()
	enemy.look_at_player()


func _on_enter() -> void:
	enter_time = Time.get_ticks_msec()
	is_pre_attack = true
	punch_alt = false


func _on_exit() -> void:
	enemy.damageEmitter.set_deferred("monitoring", false)


func process_pre_attack(delta : float):
	if Time.get_ticks_msec() - enter_time > enemy.duration_pre_punch:
		is_pre_attack = false
		return
	enter_time -= delta


func process_attack():
	if punch_alt:
		process_punch_alt()
	else:
		process_punch()


func process_punch():
	# 超过了两次攻击的间隔时间才能进入攻击准备
	if Time.get_ticks_msec() - last_attack_time < enemy.duration_between_hits:
		transition_state(BasicEnemy.STATE_IDLE)
		return

	# 打开监听，允许发生碰撞
	enemy.damageEmitter.set_deferred("monitoring", true)


func process_punch_alt():
	# 尚未达到二段攻击的时间前，先播放IDEL动画，达到后判断攻击距离决定下一步
	if Time.get_ticks_msec() - last_alt_attack_time < enemy.duration_alt_hit:
		enemy.animationPlayer.play(BasicEnemy.ANIMATION_IDLE)
		return

	if not enemy.is_player_within_attack_range():
		transition_state(BasicEnemy.STATE_IDLE)
		return

	# 打开监听，允许发生碰撞
	enemy.damageEmitter.set_deferred("monitoring", true)


func process_animation():
	if is_pre_attack:
		enemy.animationPlayer.play(BasicEnemy.ANIMATION_IDLE)
	elif punch_alt:
		enemy.animationPlayer.play(BasicEnemy.ANIMATION_PUNCH_ALT)
	else:
		enemy.animationPlayer.play(BasicEnemy.ANIMATION_PUNCH)


# 记录最后一次攻击时间，重置准备攻击时间
func reset_time():
	last_attack_time = Time.get_ticks_msec()
	last_alt_attack_time = Time.get_ticks_msec()


func process_punch_coillder():
	var orientation = enemy.character_orientation()
	if orientation == 1:
		enemy.damageEmitter.scale.x = 1
	elif orientation == -1:
		enemy.damageEmitter.scale.x = -1



func on_punch_animation_finished():
	enemy.damageEmitter.set_deferred("monitoring", false)
	punch_alt = true
	reset_time()
	if not enemy.is_player_within_attack_range():
		transition_state(BasicEnemy.STATE_IDLE)



func on_punch_alt_animation_finished():
	enemy.damageEmitter.set_deferred("monitoring", false)
	punch_alt = false
	reset_time()
	transition_state(BasicEnemy.STATE_IDLE)
